package itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import itheima.reggie.common.R;
import itheima.reggie.dto.DishDto;
import itheima.reggie.entity.Category;
import itheima.reggie.entity.Dish;
import itheima.reggie.entity.DishFlavor;
import itheima.reggie.service.CategoryService;
import itheima.reggie.service.DishFlavorService;
import itheima.reggie.service.DishService;
import itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dto) {
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        log.info(dto.toString());
        //清理对应的缓存
        String deleRedis="dish_"+dto.getCategoryId()+"_1";
        dishService.saveWithFlavor(dto);
        redisTemplate.delete(deleRedis);
        return R.success("成功");
    }

    //分页查询Raw use of parameterized class 'Page'
    @GetMapping("/page")
    public R<Page> page(long page, long pageSize, String name) {
        Page<Dish> dishPage = new Page(page, pageSize);
        Page<DishDto> dto = new Page(page, pageSize);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.orderByDesc(Dish::getCreateTime);
        if (name != null) {
            Category one = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getName, name));
            Long id = 0L;
            if (one!=null){id=one.getId();}
            lambdaQueryWrapper.like(Dish::getName, name).or(id!=0).like(Dish::getCategoryId,id);
        }
        dishService.page(dishPage, lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(dishPage, dto, "records");
        List<Dish> records = dishPage.getRecords();


        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());

        /*
        List<DishDto> list=new ArrayList<>();
        for (Dish dish:records){
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            list.add(dishDto);
        }
         */

        dto.setRecords(list);
        return R.success(dto);
    }

    //根据id查询对应的菜品信息和口味信息
    @GetMapping("/{id}")
    public R<DishDto> queryDishById(@PathVariable Long id) {
        DishDto dishDto = dishService.queryDishWithFlavorById(id);
        return R.success(dishDto);
    }

    //修改菜品信息
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dto) {
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        log.info(dto.toString());
        //清空redis里面全部缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.updateDishWithFlavor(dto);
        return R.success("成功");
    }

    @DeleteMapping
    public R<String> deleteDish(Long[] ids) {
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        log.info("删除的菜品id:" + Arrays.toString(ids));
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.deleteDishWithFlavor(ids);
        return R.success("1");
    }

    /**
     * 批量启用与停用
     */
    @PostMapping("/status/{state}")
    public R<String> convertStatus(Long[] ids, @PathVariable Integer state) {
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        Dish dish = new Dish();
        for (Long id : ids) {
            dish = dishService.getById(id);
            dish.setStatus(state);
            dishService.updateById(dish);
        }
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("1");
    }

    /*@GetMapping("/list")
    public R<List<Dish>> queryDishListById(Long categoryId,String name){
        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        lambdaQueryWrapper.like(name!=null,Dish::getName,name);

        List<Dish> list = dishService.list(lambdaQueryWrapper);
        return R.success(list);
    }
*/
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "'dish_' + #categoryId + '_ '+ 1")
    public R<List<DishDto>> queryDishListById(Long categoryId, String name) {
        List<DishDto> dtoList = null;
        String key = "dish_" + categoryId + "_" + "1";
        //从redis获取菜品数据
//        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        if (dtoList != null) {
//            //如果存在，直接返回，无需查询数据库
//            return R.success(dtoList);
//        }

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        //查询
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        dtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查到的菜品数据缓存到Redis
       // redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);
        return R.success(dtoList);
    }
}
